package ThreadDemo.src;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/*
 * Author: JacksonCoder
 * FileName: waitAndNotifyDemo
 * Version: 1.0.0
 */
public class waitAndNotifyDemo {
    public static void main(String[] args) throws InterruptedException {
        TaskQueue taskQueue = new TaskQueue();
        ArrayList<Thread> threads = new ArrayList<>();
        for(int i = 0 ; i < 5 ; i++){
            Thread t1 = new Thread(){
                public void run(){
                    while(true){
                        try{
                            String s = taskQueue.getTask();
                            System.out.println("Execute task: " + s);
                        } catch (InterruptedException e) {
                            return ;
                        }
                    }
                }
            };
            t1.start();
            threads.add(t1);
        }

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                // put task
                String s1 = "t- " + Math.random();
                System.out.println("add task: " + s1);
                taskQueue.addTask(s1);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {

                }
            }
        });
        thread1.start();
        threads.add(thread1);
        Thread.sleep(100);
        for(Thread t : threads){
            t.interrupt();
        }
    }
}

class TaskQueue {
    Queue<String> queue = new LinkedList<>();

    public synchronized void addTask(String task){
        this.queue.add(task);
        this.notify();
    }

    public synchronized String getTask() throws InterruptedException {
        while(queue.isEmpty()){
            this.wait();
        }
        return queue.remove();
    }
}
